package com.franklin.ideaplugin.easytesting.rpc;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.franklin.ideaplugin.easytesting.rpc.entity.HeartBeatData;
import com.franklin.ideaplugin.easytesting.rpc.entity.MethodInvokeData;
import com.franklin.ideaplugin.easytesting.rpc.entity.RegistryData;
import com.intellij.psi.PsiMethod;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ye Junhui
 * @since 2023/5/15
 */
public class RpcClient {

    private final static OkHttpClient okHttpClient = new OkHttpClient();

    private static final MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发送
     * @param methodInvokeData
     */
    public static void sendExecute(MethodInvokeData methodInvokeData,String port){
        if (StrUtil.isBlank(port)){
            return;
        }
        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, JSON.toJSONString(methodInvokeData));;
        final Request request = new Request.Builder()
                .url("http://127.0.0.1" + ":" + port + ServerPath.EXECUTE)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送心跳
     * @param port
     * @return
     */
    public static boolean sendHeartBeat(String port){
        if (StrUtil.isBlank(port)){
            return false;
        }
        HeartBeatData heartBeatData = new HeartBeatData();
        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, JSON.toJSONString(heartBeatData));;
        final Request request = new Request.Builder()
                .url("http://127.0.0.1" + ":" + port + ServerPath.HEART_BEAT)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            call.execute();
            return true;
        } catch (IOException e) {
             return false;
        }
    }
}
